#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Extensions/JsonExtensions 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       JSON序列化扩展方法，提供对象与JSON字符串之间的转换功能
* 类 名：       JsonExtensions
* 创建时间：  2025/5/21 18:42:47
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Common
{
    /// <summary>
    /// json 扩展
    /// </summary>
    public static class JsonExtensions
    {
        /// <summary>
        /// 默认的JSON序列化设置
        /// 1. 使用驼峰命名法
        /// 2. 忽略循环引用
        /// 3. 日期格式化为"yyyy-MM-dd HH:mm:ss"
        /// </summary>
        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };

        /// <summary>
        /// 将对象序列化为JSON字符串
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="model">要序列化的对象</param>
        /// <returns>JSON字符串，如果对象为null则返回空字符串</returns>
        public static string SerializeJson<T>(this T model)
        {
            if (model == null) return string.Empty;
            return JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// List数据序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string SerializeJson<T>(this List<T> model)
        {
            if (model == null || model.Count <= 0) return string.Empty;
            return JsonConvert.SerializeObject(model);
        }

        /// <summary>
        /// 将JSON字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T">目标对象类型</typeparam>
        /// <param name="json">JSON字符串</param>
        /// <returns>反序列化后的对象，如果字符串为空则返回默认值</returns>
        public static T DeserializeJson<T>(this string json)
        {
            if (string.IsNullOrEmpty(json)) return default(T);
            if (typeof(T) == typeof(string)) return (T)Convert.ChangeType(json, typeof(T));
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 反序列化，如果为空返回默认指
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T DeserializeJsonWithResult<T>(this string json) where T : class, new()
        {
            var result = new T();
            if (string.IsNullOrEmpty(json)) return result;
            try
            {
                result = JsonConvert.DeserializeObject<T>(json);
            }
            catch
            {
            }
            return result;
        }

        /// <summary>
        /// 序列化为WebApi类型数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string SerializeJsonWebApi<T>(this T model)
        {
            if (model == null) return string.Empty;
            return JsonConvert.SerializeObject(model, Settings);
        }

        /// <summary>
        /// 序列化为WebApi类型数据（接口使用）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string SerializeJsonWebApi<T>(this List<T> model)
        {
            if (model == null || model.Count <= 0) return string.Empty;
            return JsonConvert.SerializeObject(model, Settings);
        }
    /// <summary>
        /// 将对象深度克隆(通过JSON序列化反序列化实现)
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="source">源对象</param>
        /// <returns>克隆后的新对象</returns>
        public static T DeepClone<T>(this T source)
        {
            if (source == null) return default;
            var json = JsonConvert.SerializeObject(source);
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 将JSON字符串转换为动态对象
        /// </summary>
        /// <param name="json">JSON字符串</param>
        /// <returns>动态对象</returns>
        public static dynamic ToDynamic(this string json)
        {
            if (string.IsNullOrEmpty(json)) return null;
            return JsonConvert.DeserializeObject<dynamic>(json);
        }

        /// <summary>
        /// 判断字符串是否为有效的JSON格式
        /// </summary>
        /// <param name="json">要检查的字符串</param>
        /// <returns>如果是有效JSON返回true，否则返回false</returns>
        public static bool IsValidJson(this string json)
        {
            if (string.IsNullOrWhiteSpace(json)) return false;
            
            try
            {
                JsonConvert.DeserializeObject(json);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
